import base64
import pickle
from django_redis import get_redis_connection


def merge_cart_cookie_redis(request, response, user):
    # 合并操作
    # 获取cookie数据
    cart_cookie = request.COOKIES.get('cart_cookie')
    # cookie数据判断
    if not cart_cookie:
        return response
    # 数据解密
    cart = pickle.loads(base64.b64decode(cart_cookie.encode()))
    if cart:
        # 拆分数据
        data_dict = {}  # 保存hash数据
        # 用列表保存选中状态
        cart_selected = []
        cart_selected_no = []
        for sku_id, count_dict in cart.items():
            data_dict[int(sku_id)] = int(count_dict['count'])
            # 选中状态保存
            if count_dict['selected']:
                cart_selected.append(sku_id)
            else:
                cart_selected_no.append(sku_id)

        # 保存数据
        conn = get_redis_connection('cart')
        # 保存hash类型
        conn.hmset('cart_%s' % user.id, data_dict)
        # 选中状态
        if cart_selected:
            conn.sadd('cart_selected_%s' % user.id, *cart_selected)
        if cart_selected_no:
            conn.srem('cart_selected_%s' % user.id, *cart_selected_no)
    # 删除cookie
    response.delete_cookie('cart_cookie')
    # 返回数据
    return response